<template>
    <div>
        <div class="div-header"> <h2>卡列表与统计</h2></div>
        <el-row>
            <el-col :span="12" :offset="12">
                <el-button-group style="float: right; margin-bottom: 10px;">
                    <el-button :icon="Refresh" type="success" onclick="location.reload()" >刷新数据</el-button>
                    <el-button :icon="Refresh" type="info">refresh cache</el-button>
                </el-button-group>
            </el-col>
        </el-row>
        <div class="container mb30"> 
              <el-form style="float:right">
                      <el-form-item label="查找">
                       <el-input v-model="search"/>
                     </el-form-item>
                </el-form>
              <el-table :data="filterTableData" style="width: 100%" border>
                    <el-table-column label="会员姓名" sortable prop="memberName" />
                    <el-table-column label="卡号"  sortable prop="bindCardId" />
                    <el-table-column label="总课次"  sortable prop="totalClassTimes"  />
                    <el-table-column label="已用课次" sortable prop="usedClassTimes" />
                    <el-table-column label="剩余课次" sortable prop="remainingClassTimes" />
                    <!-- <el-table-column label="备注" sortable prop="cardNote" /> -->
                    <el-table-column label="总额" sortable prop="lumpSum" />
                    <el-table-column label="已用金额" sortable  prop="amountUsed" />
                    <el-table-column label="剩余金额"  sortable prop="balance" />
          </el-table>
           <el-row class="mt20">
            <el-col :span="20">
                <el-pagination  v-model:current-page="pageData.pageCurrent"
                :page-size="pageData.pageSize"
                 layout="prev, pager, next"   
                 :total="pageData.pageTotal"
                 background
                 size="small"
                @current-change="handleCurrentChange" />
            </el-col>
            </el-row>
            <!-- 图标数据 -->
            <el-row>
                <el-col :span="11">
                    <div ref="courseTimeDom" style="height: 400px;" class="mt20"></div>
                </el-col>
                <el-col :span="2"></el-col>
                <el-col :span="11">
                     <div ref="courseCostDom" style="height: 400px;" class="mt20"></div>
                </el-col>
            </el-row>
            
           

        </div>
        
   
    </div>
</template>

<script setup>
import {ref,reactive,computed,onMounted,onUnmounted,nextTick,onUpdated} from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import {statisticsMemberCardInfo} from '@/api/statistic'
import * as echarts from 'echarts'
//图表数据   此数据都需要从后台获取
const infoList = reactive({
    totalCourseTimeAll: 10009390,
    usedCourseTimeAll: 115,
    remainCourseTimeAll: 10009275,
    totalMoneyAll:117298,
    usedMoneyAll:111636.57,
    remainMoneyAll:5661.43
})

// 创建一个响应式引用来保存DOM元素
const courseTimeDom = ref(null);
let chartInstance =null;
//绘制课程统计 
    const option = reactive({
        // 这里是ECharts的配置项，可以根据需要绘制不同类型的图表
        title: {
            text: '课程统计图',
            subtext: `总课时${infoList.totalCourseTimeAll}`
        },
        tooltip: {},
        legend: {
            orient: 'vertical',
            left: 'right'
        },
        series: [
            {
                name: '课时',
                type: 'pie',    // 设置图表类型为饼图
                radius: '55%',  // 饼图的半径，外半径为可视区尺寸（容器高宽中较小一项）的 55% 长度。
                data: [          // 数据数组，name 为数据项名称，value 为数据项值
                    { value: infoList.usedCourseTimeAll, name: '已用课时' },
                    { value: infoList.remainCourseTimeAll, name: '剩余课时' }
                ],
                itemStyle: {
                  label: {
                      show: true,
                      formatter: '{b} : {c} ({d}%)'
                  },
                  labelLine: { show: true }
                    
                }
            }
        ]
    })
//绘制金额统计图
const  courseCostDom = ref(null)
let chartInstance2 = null;
//绘制课程统计
const option2 = reactive({
    // 这里是ECharts的配置项，可以根据需要绘制不同类型的图表
    title: {
        text: '课消金额统计图',
        subtext: `总课时${infoList.totalMoneyAll}`
    },
    tooltip: {},
    legend: {
        orient: 'vertical',
        left: 'right'
    },
    series: [
        {
            name: '课时',
            type: 'pie',    // 设置图表类型为饼图
            radius: '55%',  // 饼图的半径，外半径为可视区尺寸（容器高宽中较小一项）的 55% 长度。
            data: [          // 数据数组，name 为数据项名称，value 为数据项值
                { value: infoList.usedMoneyAll, name: '已用金额' },
                { value: infoList.remainMoneyAll, name: '剩余金额' }
            ],
            itemStyle: {
                // 将 normal 层级下的样式直接移到 itemStyle 下  
                label: {
                    show: true,
                    formatter: '{b} : {c} ({d}%)'
                },
                labelLine: {
                    show: true
                },
                color: function (params) {
                    var colorList = [
                        '#3c8282', '#ea980a', '#FFFF00', '#FF8C00', '#FF0000', '#FE8463'
                    ];
                    // 注意：这里可能需要处理 params.dataIndex 超出 colorList 长度的情况  
                    return colorList[params.dataIndex % colorList.length]; // 使用取模确保索引不会超出数组长度  
                },  
            },
              // emphasis 层级保持不变，用于定义高亮（如鼠标悬停）时的样式  
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
    ]
    })
// 初始化ECharts实例并设置配置项（这里以折线图为例，但可灵活替换）
onUpdated(async () => {
    await nextTick(()=>{   
        // 检查DOM元素是否存在    初始化饼状图
            if (courseTimeDom.value) {
                chartInstance = echarts.init(courseTimeDom.value)
                chartInstance.setOption(option)
            }

            if (courseCostDom.value) {
                chartInstance2 = echarts.init(courseCostDom.value)
                chartInstance2.setOption(option2)
            }

    }) // 确保DOM已经渲染完成  
     
})

// 销毁ECharts实例
onUnmounted(() => {
    console.log('销毁----')
    if (chartInstance != null && chartInstance.dispose) {
        chartInstance.dispose();
    }
})


const pageData = reactive({
    pageCurrent: 1,
    pageSize: 5,
    pageTotal: 10
})
const handleCurrentChange = (val) => {
    console.log(`current page: ${val}`)
    pageData.pageCurrent = val
    getData()
}

const search = ref('')
const filterTableData = computed(() =>
    tableData.value.filter(
        (data) =>
            !search.value ||
            data.memberName.toLowerCase().includes(search.value.toLowerCase())||data.bindCardId==search.value
    )
)
//操作记录的数据模拟
const tableData = ref([])

//点击操作记录按钮 
const getData = (row) => {
    //todo 调用接口 查询操作记录
    statisticsMemberCardInfo().then(res => {
         //todo 如下实现的分页是假分页  需要后端返回真分页的数据  总数据量 
        let start = (pageData.pageCurrent - 1) * pageData.pageSize;//开始位置
        let end = pageData.pageCurrent * pageData.pageSize;//结束位置 数组的截取的时候 [start,end) suo所以不用-1 
        tableData.value = res.data.slice(start, end)
        // tableData.value = res.data
        pageData.pageTotal=res.data.length
    })
    
}
getData()




</script >
<style lang="less" scoped>
.mb30{
    margin-bottom: 30px;
}
.div-header{
    background-color: #fff;
    padding: 10px 20px;
}
.mt20{
    margin-top: 20px;
}
</style>